const app = getApp()

const defaultAvatarUrl = 'https://dev.yueyoumap.com/admin-api/infra/file/1632294943085215745/get/50e34af178b7249c78f9e611539f3a8eeba02272066cc99f416880f5d1ee954a.png'


Page({
  data: {
    avatarUrl: defaultAvatarUrl,
    nickname: 'ID：456790',
    motto: "",
    showAll: false,
    theme: wx.getSystemInfoSync().theme,
  },

  onChooseAvatar(event) {
    const { avatarUrl } = event.detail 
    this.setData({
      avatarUrl: avatarUrl,
    })
  },
  
  getInputNickname(event){
    this.setData({
      nickname: event.detail.value
    })
  },

  getInputSign(event){
    this.setData({
      motto: event.detail.value
    })
  },
  
  tapSubmit(){
    // console.log("点击submit按钮！",this.data.avatarUrl,this.data.nickname)
    let that=this;
    if(that.data.avatarUrl===defaultAvatarUrl){
        if(that.data.nickname){
            wx.showModal({
                title: '头像提示',
                content: '您没有选择头像，将使用默认头像；如需更改，点击取消，然后头像上方选择自定义头像',
                success (res) {
                    if (res.confirm) {
                        console.log("点击submit按钮！",that.data.avatarUrl,that.data.nickname)
                        that.uploadUserinfo(that.data.nickname,that.data.avatarUrl,true)
                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
        }
        else{
            wx.showToast({
                title: '请输入昵称！',
                icon: "error"
            }) 
        }
    }
    else{
        if(that.data.nickname){
            console.log("点击submit按钮！",that.data.avatarUrl,that.data.nickname)
            that.uploadUserinfo(that.data.nickname,that.data.avatarUrl,false)
        }
        else{
            wx.showToast({
                title: '请输入昵称！',
                icon: "error"
            }) 
        }
    }
  },

  uploadUserinfo(minenickName, mineavatarUrl, isDefault){
    wx.request({
        // url: this.globalData.url + '/login',
        url: app.globalData.server+'/app-api/member/user/update-nickname',
        header:{
        "Authorization": 'Bearer ' + wx.getStorageSync('accessTokenData').accessToken,
        'content-type':'application/x-www-form-urlencoded'
        },
        data:{
            nickname: minenickName
        },
        method: "put",
        success: (res) => {
        console.log("上传昵称成功：",res)
        if(isDefault){
            this.saveCardAndUpLoadAvatar(mineavatarUrl) //下载并上传图片
        }
        else if(mineavatarUrl.slice(0,25) != "https://dev.yueyoumap.com"){
            this.uploadAvatar(mineavatarUrl) // 上传图片
        }
        else{
            if(this.data.motto.length>0){
              this.uploadMotto()
            }
            else{
              wx.showToast({
                title: '成功修改信息',
                icon: 'success',
                duration: 2000
              })
              // 刷新个人用户信息
              app.globalData.freshUserInfo=true
              wx.navigateBack({
                delta: 1,
              })
            }
        }
        },
        fail: (err) => {
            console.log(err);
        },
        complete:()=>{
            wx.hideLoading();
        }
    })
  },

  // 保存图片(主要针对授权的几种不同情况判断)
  saveCardAndUpLoadAvatar(avatarFilename) {
    let that = this
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.writePhotosAlbum']) {
          that.saveImg(avatarFilename)
        } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              that.saveImg(avatarFilename)
            },
            fail() {
              wx.showToast({
                title: '您没有授权，无法保存到相册',
                icon: 'none'
              })
            }
          })
        } else {
          wx.openSetting({
            success(res) {
              if (res.authSetting['scope.writePhotosAlbum']) {
                that.saveImg(avatarFilename)
              } else {
                wx.showToast({
                  title: '您没有授权，无法保存到相册',
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
  },

  saveImg(avatarFilename) {
    let that = this;
    //文件名设置为时间戳
    let fileName = new Date().valueOf();
    wx.downloadFile({ //下载图片到本地
      url: avatarFilename,      
      filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.png',
      success(res) {
        console.log("下载头像的结果是：",res)
        if (res.statusCode === 200) {
          let img = res.filePath
          console.log(img)
          that.uploadAvatar(img)
        }
      },
      fail(err){
        wx.showModal({
          title: '下载头像失败',
          content: JSON.stringify(err)+avatarFilename,
          fail: (err) => {
            console.log(err);
          },
          complete:()=>{
            wx.hideLoading();
          }
        })
      }
    })
  },

  // 上传图片
  uploadAvatar(file) {
    wx.uploadFile({
      filePath: file, // 上一步操作中带过来的文件
      name: 'avatarFile', // 接口中要求的formData类型数据的参数
      url: app.globalData.server + '/app-api/member/user/update-avatar', // 接口
      header:{
        "Authorization": 'Bearer ' + wx.getStorageSync('accessTokenData').accessToken
      },
      formData: { // 其他数据类型的参数
      },
      success: res => {
        let avatarContent=JSON.parse(res.data)
        console.log('上传头像成功，头像地址是：', avatarContent.data);
        if(this.data.motto.length>0){
          this.uploadMotto()
        }
        else{
          wx.showToast({
            title: '成功登录',
            icon: 'success',
            duration: 2000
          })
          // 刷新个人用户信息
          app.globalData.freshUserInfo=true
          wx.navigateBack({
            delta: 1,
          })
        }
        
      },
      fail: err => {
        wx.showModal({
            title: '上传图片错误',
            content: JSON.stringify(err)
        })
      }
    })
  },

  // 上传签名
  uploadMotto(){
    wx.request({
        url: app.globalData.server+'/app-api/member/user/motto',
        header:{
        "Authorization": 'Bearer ' + wx.getStorageSync('accessTokenData').accessToken,
        'content-type':'application/x-www-form-urlencoded'
        },
        data:{
            motto: this.data.motto
        },
        method: "put",
        success: (res) => {
        console.log("上传个性签名成功，返回结果是：",res)
          wx.showToast({
            title: '成功修改信息',
            icon: 'success',
            duration: 2000
          })
          // 刷新个人用户信息
          app.globalData.freshUserInfo=true
          wx.navigateBack({
            delta: 1,
          })
        },
        fail: (err) => {
            console.log(err);
        },
        complete:()=>{
            wx.hideLoading();
        }
    })
  },


  onLoad(options) {
    wx.onThemeChange((result) => {
      this.setData({
        theme: result.theme
      })
    })

    // 编辑或者获取用户昵称头像
    console.log("接收的参数是：",options)
    if(options.userInfo){
      let userInfo = JSON.parse(options.userInfo)
      this.setData({
        avatarUrl: userInfo.avatar,
        nickname: userInfo.nickname,
        motto: userInfo.motto,
        showAll: true,
      })
    }
  },

})
